package part_11_Deadlock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Runner {

	private Account acc1 = new Account();
	private Account acc2 = new Account();

	private Lock lock1 = new ReentrantLock();
	private Lock lock2 = new ReentrantLock();

	private void aquireLocks(Lock firstlock, Lock secondlock) throws InterruptedException {

		while (true) {
			
			if (firstlock.tryLock() && secondlock.tryLock()) {

				return;
			} else if (firstlock.tryLock()) {

				firstlock.unlock();

			} else if (secondlock.tryLock()) {

				secondlock.unlock();

			}

			Thread.sleep(1);
			
			
		}

	}

	public void firstThread() throws InterruptedException {

		Random ran = new Random();

		for (int i = 0; i < 10000; i++) {

			lock1.lock();
			lock2.lock();

			try {
				Account.transfer(acc1, acc2, ran.nextInt(100));
			} finally {

				lock1.unlock();
				lock2.unlock();
			}

		}

	}

	public void secondThread() throws InterruptedException {
		Random ran = new Random();

		for (int i = 0; i < 10000; i++) {
			// always lock your locks in the same order in order to avoid the
			// deadlock situation
			lock1.lock();
			lock2.lock();

			try {
				Account.transfer(acc2, acc1, ran.nextInt(100));
			} finally {

				lock1.unlock();
				lock2.unlock();
			}
		}
	}

	public void finished() {

		System.out.println("Balance in Account1 :: " + acc1.getBalance());
		System.out.println("Balance in Account2 :: " + acc2.getBalance());
		System.out.println("Balance in Both Accounts :: "
				+ (acc1.getBalance() + acc2.getBalance()));

	}

}
